package com.value.utils;

import com.value.vo.ValueVO;

import java.lang.reflect.Field;
import java.util.*;


public class CollectionUtils {
    /**
     * 分离出新增和更新的对象
     *
     * @param source
     * @param insertList
     * @param updateList
     * @param existsId
     */
    public static <T> void separateIU(List<T> source, List<T> insertList,
                                      List<T> updateList, List<Long> existsId,
                                      String masterField, Long masterId) {
        if (source == null || source.isEmpty() || insertList == null || updateList == null || existsId == null) {
            return;
        }
        try {
            Field field = source.get(0).getClass().getDeclaredField("id");
            field.setAccessible(true);
            Field master = null;
            if (masterField!=null){
                master = source.get(0).getClass().getDeclaredField(masterField);
                master.setAccessible(true);
            }
            for (T obj : source) {
                ValueVO baseVO = (ValueVO) obj;
                baseVO.setDataChange(false);
                if (field.get(obj) != null && Long.valueOf(field.get(obj).toString()) > 0) {
                    baseVO.setModifiedInfor();
                    updateList.add(obj);
                    existsId.add(Long.valueOf(field.get(baseVO).toString()));
                } else {
                    baseVO.setCreatedInfor();
                    if (masterField!=null){
                        master.set(obj, masterId);
                    }
                    insertList.add(obj);
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断集合是为null或空
     *
     * @param <T>
     * @param list
     * @return
     */
    public static <T> boolean isEmpty(List<T> list) {
        if (list == null || list.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断集合不是为null或空
     *
     * @param <T>
     * @param list
     * @return
     */
    public static <T> boolean isNotEmpty(List<T> list) {
        return !isEmpty(list);
    }

    public static <K, V> List<V> getValue(Map<K, V> map) {
        List<V> value = new ArrayList<V>();
        if (map == null || map.isEmpty()) {
            return value;
        }
        Set<Map.Entry<K, V>> set = map.entrySet();
        Iterator<Map.Entry<K, V>> it = set.iterator();
        while (it.hasNext()) {
            value.add(it.next().getValue());
        }
        return value;
    }
}
